package com.simple.deploy.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simp.costant.Constant;
import com.simp.page.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author pan.shun
 * @since 2022/3/15 17:17
 */
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

    private RestTemplate restTemplate;

    private String requestUrl;

    AdminInterceptor(RestTemplate restTemplate, String requestUrl) {
        this.requestUrl = requestUrl;
        this.restTemplate = restTemplate;
    }

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if ("OPTIONS".equals(request.getMethod())) {
            log.info("CORS跨域复杂请求发送一个方法为OPTIONS的预检请求");
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        JSONObject responseMessage;
        String forObject;
        if (!StringUtils.isEmpty(requestUrl) && !"null".equals(requestUrl)) {
            try {
                forObject = restTemplate.getForObject(requestUrl + "/common/check?token=" + getToken(request), String.class);
                responseMessage = JSON.parseObject(forObject);
            } catch (ResourceAccessException e) {
                log.info("上游系统处于重启中，权限放行");
                return true;
            }

            if (responseMessage.getInteger("code").equals(200)) {
                log.info("上游系统验证通过,开始进行资源的访问");
                return true;
            } else {
                log.info("验证失败，暂不可进行访问");
                sendResponse(response, forObject);
                return false;
            }
        } else {
            log.info("当前尚未进行权限认证路径的配置，故拦截放行 【可以在配置文件中添加 {simple-label-core} 进行设置 】");
            return true;
        }
    }

    private String getToken(HttpServletRequest request) {
        String header = request.getHeader(Constant.TOKEN_CONFIG.TOKEN_KEY);
        if (StringUtils.isEmpty(header) || "null".equals(header)) {
            header = request.getParameter(Constant.TOKEN_CONFIG.TOKEN_KEY);
        }
        if (!StringUtils.isEmpty(header) && !"null".equals(header)) {
            return header;
        } else {
            return "";
        }
    }

    private void sendResponse(HttpServletResponse response, String resp) {
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = new PrintWriter(response.getOutputStream());
            pw.write(resp);
            pw.close();
        } catch (IOException e) {
            log.error("响应异常 :{}", e);
        }
    }


    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
